package com.processmanager.service;

import com.processmanager.sdk.model.ProcessLog;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;

/**
 * WebSocket消息服务
 * 
 * <p>负责通过WebSocket向客户端推送实时消息：</p>
 * <ul>
 *   <li>进程日志实时推送</li>
 *   <li>进程状态变更通知</li>
 *   <li>系统消息广播</li>
 * </ul>
 * 
 * @author ProcessManager
 * @version 1.0.0
 * @since 2024-01-01
 */
@Service
public class WebSocketService {
    
    private static final Logger logger = LoggerFactory.getLogger(WebSocketService.class);
    
    private final SimpMessagingTemplate messagingTemplate;
    
    /**
     * 构造函数
     * 
     * @param messagingTemplate WebSocket消息模板
     */
    public WebSocketService(SimpMessagingTemplate messagingTemplate) {
        this.messagingTemplate = messagingTemplate;
    }
    
    /**
     * 推送进程日志到指定进程的订阅者
     * 
     * @param processId 进程ID
     * @param log 日志条目
     */
    public void pushProcessLog(String processId, ProcessLog log) {
        try {
            String destination = "/topic/process/" + processId + "/logs";
            messagingTemplate.convertAndSend(destination, log);
            logger.debug("推送日志到进程 {}: {}", processId, log.getMessage());
        } catch (Exception e) {
            logger.error("推送进程日志失败: {}", e.getMessage(), e);
        }
    }
    
    /**
     * 推送进程状态更新
     * 
     * @param processId 进程ID
     * @param status 进程状态
     */
    public void pushProcessStatus(String processId, String status) {
        try {
            String destination = "/topic/process/" + processId + "/status";
            messagingTemplate.convertAndSend(destination, status);
            logger.debug("推送状态更新到进程 {}: {}", processId, status);
        } catch (Exception e) {
            logger.error("推送进程状态失败: {}", e.getMessage(), e);
        }
    }
    
    /**
     * 推送系统消息到所有客户端
     * 
     * @param message 系统消息
     */
    public void pushSystemMessage(String message) {
        try {
            messagingTemplate.convertAndSend("/topic/system", message);
            logger.debug("推送系统消息: {}", message);
        } catch (Exception e) {
            logger.error("推送系统消息失败: {}", e.getMessage(), e);
        }
    }
    
    /**
     * 推送进程列表更新
     * 
     * @param processList 进程列表
     */
    public void pushProcessListUpdate(Object processList) {
        try {
            messagingTemplate.convertAndSend("/topic/processes", processList);
            logger.debug("推送进程列表更新");
        } catch (Exception e) {
            logger.error("推送进程列表更新失败: {}", e.getMessage(), e);
        }
    }
} 